<template>
  <div class="flex">
    <el-select clearable placeholder="请选择省份" v-model="state.province">
      <el-option
        v-for="item in state.areas"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      />
    </el-select>
    <el-select
      clearable
      :disabled="!state.province"
      style="margin: 0 10px"
      placeholder="请选择城市"
      v-model="state.city"
    >
      <el-option
        v-for="item in selectCity"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      />
    </el-select>
    <el-select
      clearable
      :disabled="!state.province || !state.city"
      placeholder="请选择区域"
      v-model="state.area"
    >
      <el-option
        v-for="item in selectArea"
        :key="item.code"
        :value="item.code"
        :label="item.name"
      />
    </el-select>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import allAreas from '../lib/pca-code.json'

// Define reactive state
const state = ref({
  province: '',
  city: '',
  area: '',
  areas: allAreas,
})

// Computed properties for selectCity and selectArea
const selectCity = computed(() => {
  const selectedProvince = state.value.areas.find(
    (item) => item.code === state.value.province,
  )
  return selectedProvince ? selectedProvince.children : []
})

const selectArea = computed(() => {
  const selectedCity = selectCity.value.find(
    (item) => item.code === state.value.city,
  )
  return selectedCity ? selectedCity.children : []
})

const emit = defineEmits(['change'])

watch(
  () => state.value.province,
  (newProvince) => {
    state.value.city = ''
    state.value.area = ''
  },
)

watch(
  () => state.value.city,
  (newCity) => {
    state.value.area = ''
  },
)

watch(
  () => state.value.area,
  (newArea) => {
    if (newArea) {
      const provinceData = {
        code: state.value.province,
        name:
          allAreas.find((item) => item.code === state.value.province)?.name ||
          '',
      }
      const cityData = {
        code: state.value.city,
        name:
          selectCity.value.find((item) => item.code === state.value.city)
            ?.name || '',
      }
      const areaData = {
        code: newArea,
        name:
          selectArea.value.find((item) => item.code === newArea)?.name || '',
      }
      emit('change', {
        province: provinceData,
        city: cityData,
        area: areaData,
      })
    }
  },
)
</script>
